$(function () {
    //  按钮生成器
    generateButton($('#north'), getExtendToolbarBtns());
    let columns = [[
        // {field: 'id', title: '主键', align: 'center', halign: 'center', sortable: true, hidden: true},
        {
            field: 'ctCode', width: 100, title: '编号', align: 'center', halign: 'center', sortable: true, editor: {
                type: 'textbox', options: {required: true}
            }
        },
        {
            field: 'ctName', width: 100, title: '名称', align: 'center', halign: 'center', sortable: true, editor: {
                type: 'textbox', options: {required: true}
            }
        },
        {
            field: 'ctContactPerson',
            width: 100,
            title: '联系人',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'textbox', options: {}
            }
        },
        {
            field: 'fax',
            width: 100,
            title: '传真',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'textbox', options: {}
            }
        },
        {
            field: 'ctContactPhone',
            width: 100,
            title: '联系电话',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'textbox', options: {}
            }
        },
        {
            field: 'sendAddress01',
            width: 150,
            title: '发货地址1',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'textbox', options: {}
            }
        },
        {
            field: 'sendAddress02',
            width: 150,
            title: '发货地址2',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'textbox', options: {}
            }
        },
        {
            field: 'sendAddress03',
            width: 150,
            title: '发货地址3',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'textbox', options: {}
            }
        },


        {
            field: 'ctState', width: 50, title: '状态', align: 'center', halign: 'center', sortable: true, editor: {
                type: 'combobox', options: {
                    data: [{id: 1, text: '正常'}, {id: 0, text: '停用'}],
                    value: 1,
                    panelHeight: 'auto',
                    textField: 'text',
                    valueField: 'id',
                    editable: false,
                    required: true
                }
            },
            formatter: (v, r, i) => {
                return v == 1 ? '正常' : '停用';
            }
        },
    ]];
    setDatagridColumnOpts($('body').data('menu_id'), $('#e_grid'), columns, edatagrid);
    bindEnterEvents();
    //主表格单击事件
    $('#e_grid').datagrid({
        onClickRow: function (index, row) {
            // initGridUpload(row.ctCode, 0);//2024年10月9日 添加上传合同功能
        }
    })

    $.uploadComponent({
        url: 'jcShearingFactory/upload',
        method: 'POST',
        fields: columns[0],
        onSuccess: function (data) {
            if (data.success) {
                $.uploadComponent('close');
                $('#e_grid').edatagrid('reload');
                $.messager.show({title: '提示', msg: data.message});
            } else {
                $(this).edatagrid('cancelRow');
                $(this).edatagrid('editRow', index);
                $.messager.alert('提示', '上传失败!' + data.message, 'error');
            }
        }
    })
})

function edatagrid(columns) {
    $('#e_grid').edatagrid({
        method: 'GET',
        param: {},
        url: 'jcShearingFactory/listQuery',
        saveUrl: 'jcShearingFactory/insertSelective',
        updateUrl: 'jcShearingFactory/updateSelective',
        destroyUrl: 'jcShearingFactory/deleteByPk',
        idField: 'id',
        destroyMsg: {
            norecord: {	// when no record is selected
                title: '警告',
                msg: '未选中任何数据'
            },
            confirm: {	// when select a row
                title: '确认',
                msg: '确定删除吗?删除后不可恢复!'
            }
        },
        loadFilter: pageFilter,
        pagination: true,
        columns: columns,
        // pagePosition: 'top',
        pageSize: 200,
        pageNumber: 1,
        pageList: [200, 400, 600, 800, 1000],
        striped: true,
        fit: true,
        sortable: true,
        rownumbers: true,
        remoteSort: false,
        showFooter: true,
        singleSelect: true,
        onLoadSuccess: function () {
            $(this).datagrid('enableFilter');
            $(this).data('edatagrid').options.editIndex = -1;
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('enable');
                }
            })
        },
        onLoadError: function () {
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('enable');
                }
            })
        },
        onBeforeLoad: function (param) {
            $(this).datagrid('destroyFilter');
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('disable');
                }
            })
            return true;
        },
        onSuccess: function (index, row) {
            $(this).edatagrid('reload');
            if (row.success) {
                $.messager.show({title: '提示', msg: row.message});
            } else {
                $(this).edatagrid('enableEditing');
                $.messager.alert('提示', row.message, 'warning')
            }
        },
        onDestroy: function (index, row) {
            $(this).edatagrid('reload');
            if (row.success) {
                // $.messager.show({title: '提示', msg: row.message});
            } else {
                $.messager.alert('提示', row.message, 'warning')
            }
        },
        onError: function (index, row) {
            $.messager.show({title: '提示', msg: row.message});
        },
        onResizeColumn: function (f, w) {
            columnResizeEvent($('body').data('menu_id'), f, w);
        },
    })
}

function btn_search() {
    $('#e_grid').edatagrid('reload');
}

function btn_add() {
    $('#e_grid').edatagrid('addRow');
}

function btn_modify() {
    let selected = $('#e_grid').edatagrid('getSelected');
    if (selected != undefined) {
        let index = $('#e_grid').edatagrid('getRowIndex', selected);
        if (index != -1) {
            $('#e_grid').edatagrid('editRow', index);
        }
    } else {
        $.messager.alert('提示', '点击鼠标左键选中行后再执行本功能', 'warning');
    }
}

function btn_delete() {
    let selected = $('#e_grid').edatagrid('getSelected');
    if (selected != undefined) {
        let index = $('#e_grid').edatagrid('getRowIndex', selected);
        if (index != -1) {
            $('#e_grid').edatagrid('destroyRow', index);
        }
    } else {
        $.messager.alert('提示', '点击鼠标左键选中行后再执行本功能', 'warning');
    }
}

//  导入Excel
function btn_import() {
    $.uploadComponent('open');
}

function btn_save() {
    $('#e_grid').edatagrid('saveRow');
}

function btn_export() {
    exportExcel('#e_grid', '往来单位');
}

function getExtendToolbarBtns() {
    let buttonOpts = [
        {id: 'btn_arrowup', text: '上移', iconCls: 'icon-arrow_up', onClick: btn_arrowup, plain: true},
        {id: 'btn_arrowdown', text: '下移', iconCls: 'icon-arrow_down', onClick: btn_arrowdown, plain: true},
        {id: 'btn_first', text: '第一', iconCls: 'icon-arrow_redo', onClick: btn_arrowfirst, plain: true},
        {id: 'btn_last', text: '最后', iconCls: 'icon-arrow_undo', onClick: btn_arrowlast, plain: true},
        // {id: 'btn_upload', text: '上传文件', iconCls: 'icon-add', onClick: btn_upload, plain: true},
        // {id: 'btn_test', text: '测试', iconCls: 'icon-arrow_down', onClick: btn_test, plain: true},
    ]

    return buttonOpts;
}

function btn_arrowfirst() {
    let datagrid = $('#e_grid');
    let selected = datagrid.datagrid('getSelected');
    let selectRowIndex = datagrid.datagrid('getRowIndex', selected);
    if( selectRowIndex == 0 ){
        $.messager.alert('提示', '选中了第一行，无需再设置为第一行', 'warning');
        return;
    }
    if (selectRowIndex > 0) {
        datagrid.datagrid('deleteRow', selectRowIndex);
        datagrid.datagrid('insertRow', {
            index: 0,
            row: selected
        });
        datagrid.datagrid('selectRow', 0);
        moveClientSeqSelectedRow(selected, 2)
    } else {
        $.messager.alert('提示', '未选中', 'warning')
    }
}

function btn_arrowlast() {
    let datagrid = $('#e_grid');
    let selected = datagrid.datagrid('getSelected');
    let selectRowIndex = datagrid.datagrid('getRowIndex', selected);
    let allRows = $('#e_grid').datagrid('getRows') || [];
    if( selectRowIndex == allRows.length ){
        $.messager.alert('提示', '选中了最后一行，无需再设置为最后一行', 'warning');
        return;
    }
    if (selectRowIndex >= 0) {
        datagrid.datagrid('deleteRow', selectRowIndex);
        datagrid.datagrid('insertRow', {
            index: allRows.length,
            row: selected
        });
        datagrid.datagrid('selectRow', selectRowIndex);
        moveClientSeqSelectedRow(selected, 3)
    } else {
        $.messager.alert('提示', '未选中', 'warning')
    }
}

function btn_upload() {
    let panel = $('#layout').layout('panel', 'south');
    let height = panel.panel('options').height;
    if (height <= 32)
        panel.panel('resize', {
            height: 320
        })
    else
        panel.panel('resize', {
            height: 32
        })
    $('#layout').layout('resize')
    //获取选中行
    var selectedRow = $('#e_grid').datagrid('getSelected');
    if (selectedRow) {
        console.log(selectedRow);
        // initGridUpload(selectedRow.ctCode, 0);
        initDrawingForm()
    }
}

function btn_test(){
    // const rows = $('#e_grid').datagrid('getRows')
    // console.log(rows);
}

function btn_arrowup() { // 上移
    let datagrid = $('#e_grid');
    let selected = datagrid.datagrid('getSelected');
    let selectRowIndex = datagrid.datagrid('getRowIndex', selected);
    if( selectRowIndex == 0 ){
        $.messager.alert('提示', '选中了第一行，无需再设置为第一行', 'warning');
        return;
    }
    if (selectRowIndex > 0) {
        datagrid.datagrid('deleteRow', selectRowIndex);
        datagrid.datagrid('insertRow', {
            index: --selectRowIndex,
            row: selected
        });
        datagrid.datagrid('selectRow', selectRowIndex);
        moveClientSeqSelectedRow(selected, 0)
        //resetIndex(datagrid, datagrid.datagrid('getRows') || []);
    } else {
        $.messager.alert('提示', '未选中', 'warning')
    }
}

function btn_arrowdown() { // 向下
    let datagrid = $('#e_grid');
    let selected = datagrid.datagrid('getSelected');
    let selectRowIndex = datagrid.datagrid('getRowIndex', selected);
    if (selectRowIndex < datagrid.datagrid('getRows').length - 1) {
        datagrid.datagrid('deleteRow', selectRowIndex);
        datagrid.datagrid('insertRow', {
            index: ++selectRowIndex,
            row: selected
        });
        datagrid.datagrid('selectRow', selectRowIndex);
        moveClientSeqSelectedRow(selected, 1)
        //resetIndex(datagrid, datagrid.datagrid('getRows') || [])
    } else {
        $.messager.alert('提示', '未选中', 'warning')
    }
}

function resetIndex(grid, rows) {
    let i = 0;
    let r = rows.map(item => {
        item['seq'] = ++i;
        return item;
    })
    $(grid).edatagrid('laodData', [...r]);
}

function moveClientSeqSelectedRow(selectedRow, direction){
    if( !selectedRow ) return
    const id = selectedRow.id;
    moveClientSeq(id, direction);
}
/**
 * 2021年9月27日 10:57:00 chanchaw
 * @param id 选中行的 id
 * @param direction 移动方向：0 - 向上移动，1 - 向下移动，2 - 第一，3 - 最后
 */
function moveClientSeq(id, direction){
    $.ajax({
        type : "GET",
        url : `jcShearingFactory/seq/${id}/${direction}`,
        contentType: "application/json;charset=UTF-8",
        success : function(result) {
        },
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        },
        complete: function () {
        }
    })

}

// 上传结束后调用 - 不可删除
// function afterUpload(){
//     let selectdeRow = $('#e_grid').datagrid('getSelected');
//     initGridUpload(selectdeRow.ctCode, 0);
//     // 初始化用于上传的 form
//     initDrawingForm();
// }

// 初始化用于上传的 form
function initDrawingForm(){
    // 初始化用于上传的几个控件的值
    $('#fileUpload').val('');
    $('#fileRename').val('');
    $('#remark').val('');
    document.form_dlg_upload.submitbtn.disabled = false;
}

// 用户选择文件后触发本函数
function handleFiles(files){
    if( !files || files.length<=0 ) return;
    const file = files[0];
    const fileName = file.name; // 带有扩展名的完整文件名
    fileNameArray = fileName.split('.');
    const fileNamePre = fileNameArray[0];
    const fileNameSuffix = fileNameArray[1];

    $('#fileRename').val(fileNamePre);
}

// 提交表单按钮触发的事件
function submitUpload(){
    // 检查上传文件的权限
    $.ajax({
        type : "GET",
        contentType: "application/json;charset=UTF-8",
        url : "sysPermission/getObjectPermission/401",
        async: false,
        success : function(res) {
            if( !res.success ){
                $.messager.alert("提示",res.message,"错误");
                return;
            }
            const perms = res.data;
            console.log(perms);
            /*if( !perms || perms.length <= 0 ){
                $.messager.alert("提示","没有权限！","错误");
                return;
            }

            let perm = 0;
            for (let i = 0; i < perms.length; i++) {
                const has = perms[i]['sysMoney'];
                perm += has;
            }
            if( perm <=0 ){
                $.messager.alert("提示","没有权限！","错误");
                return;
            }*/

            // 有权限执行则禁用提交按钮，防止多次操作
            document.form_dlg_upload.submitbtn.disabled = true;
        },
        //请求失败，包含具体的错误信息
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        },
        complete: function () {
        }
    })

}

function handleFiles(files){
    // 将全局存货编码主键保存到表单控件中
    let selectedRow = $('#e_grid').datagrid('getSelected');
    if (!selectedRow) {return;}
    $('#contactCode').val(selectedRow.ctCode);

    if( !files || files.length<=0 ) return;
    const file = files[0];
    const fileName = file.name; // 带有扩展名的完整文件名
    $('#filenameOriginal').val(fileName);
    fileNameArray = fileName.split('.');
    const fileNamePre = fileNameArray[0];
    const fileNameSuffix = fileNameArray[1];

    $('#fileRename').val(fileNamePre);
}

/**
 * 2024年10月9日 gaowt
 * 新增上传合同功能
 */
/*function initGridUpload(contactCode, type){
    let start = $('#start').datebox('getValue') || '';
    let end = $('#end').datebox('getValue') || '';
    $("#grid_upload").edatagrid({
        url: `uploadContract/selectByContactCode/${contactCode}/${type}?start=${start}&end=${end}`,
        striped: true,
        sortable: true,
        rownumbers: true,
        method: 'POST',
        remoteSort: false,
        singleSelect: true,
        sortName: 'createTime', // 要排序的字段名
        sortOrder: 'desc', // 设置为 'desc' 进行降序排序
        columns: [[
            { field: "id", title: '主键', hidden: true, width: 50 },
            { field: "createTime", title: "上传时间", hidden:false,
                formatter:function(val){
                    return DatetimeUtils.dateToStr('yyyy-MM-dd',new Date(val));
                }},
            { field: "createUser", title: "上传用户",width:300 },
            { field: "filenameRename", title: "文件名",width:200,
                editor: {
                    type: 'textbox', options: {}
                }},
            { field: "remark", title: "备注",width:150, editor: {
                    type: 'textbox', options: {}
                }},
            { field: "action", title: "操作",width:80,
                formatter:function(val,rowData,rowIndex){
                    const downloadFileName = getDownloadFileName(rowData);
                    const drawingLink = getDrawingFileLink(rowData.hashString);
                    return `<div align="center" style="width:100%;"><a href=${drawingLink} target="view_window" download=${downloadFileName}> 下载 </a></div>`;
                }}
        ]],
        onLoadSuccess: function (data) {
            console.log(data)
        },
        onDblClickRow: function(index, row) {
            $(this).edatagrid('beginEdit', index);
        },
        onBeforeLoad: function (param) {
            console.log(param);
            return true;
        },
        onClickRow: function(index,row){
        },
        onLoadError: function (e) {
            console.log(e)
        },
        toolbar: [
            {
                iconCls: 'icon-reload', text: '刷新', handler: refresh
            },
            {
                iconCls: 'icon-edit', text: '修改', handler: editRow
            },
            {
                iconCls: 'icon-cancel', text: '删除', handler: removeRow
            }
        ]
    });

    function refresh() {
        $('#grid_upload').edatagrid('reload');
    }

    function editRow() {
        $('#grid_upload').edatagrid('saveRow');
        let selected = $('#grid_upload').edatagrid('getSelected');
        if( !selected ) {
            $.messager.alert("警告", "选中行后再执行本操作！");
        }else {
            $.ajax({
                url: 'uploadContract/updateByPrimaryKeySelective',
                data: JSON.stringify(selected),
                contentType: 'application/json; charset=utf-8', // 指定字符集
                type: 'POST',
                dataType: 'json',
                success: function (res) {
                    if (res.data > 0) {
                        $.messager.show({title: '提示', msg: '成功'});
                        initGridUpload(selected.contactCode, selected.type);
                    }
                }
            })
        }
    }

    function removeRow() {
        var selectedRow = $('#grid_upload').edatagrid('getSelected');
        if( !selectedRow ){
            $.messager.alert("警告","选中行后再执行本操作！");
        }else {
            $.messager.confirm('提示', '是否删除', function (r) {
                if (r) {
                    $.ajax({url: `uploadContract/delete/${selectedRow.id}`, type: 'POST', dataType: 'json'})
                        .then(function (res) {
                            if (res.data == 1) {
                                $('#grid_upload').edatagrid('reload');
                                // 刷新上面存货档案表格并选中当前被选中的行
                                let drawingRows = $('#grid_upload').edatagrid('getRows') || [];
                                if(drawingRows.length === 1){// 没有合同了则刷新存货档案表格数据
                                    btn_search();
                                }
                            }else{
                                $.messager.alert('提示', res.message, 'error');
                            }
                        }).catch( err => {
                        alert('删除上传记录时出现异常！');
                        $.messager.alert('提示', '服务器连接失败!', 'error');
                    })
                }
            })
        }
    }

    function getDownloadFileName(rowData){
        const filenameOriginal = rowData['filenameOriginal'];
        const filenameRename = rowData['filenameRename'];
        const extension = getFileExtension(rowData.hashString);
        let downloadFileName = '';
        if( !filenameRename || filenameRename.length<=0 )
            downloadFileName = filenameOriginal;
        else
            downloadFileName = filenameRename + '.' + extension;
        return downloadFileName;
    }

    // 拼接文件名得到文件的绝对路径并返回
    function getDrawingFileLink(fileName){
        return '/xzy/uploadcontractclient/' + fileName;
    }
}*/

function upload_search() {
    let selectedRow = $('#e_grid').datagrid('getSelected');
    // if (selectedRow) {initGridUpload(selectedRow.ctCode, 0);}
}